<template>
  <div>
    <!-- {{store.getters['cate/getCate']}} -->
    <el-dialog
      v-model="props.isShow"
      :title="props.isAdd ? '添加菜单' : '编辑菜单'"
      center
      :before-close="cancel"
    >
      <el-form ref="goodsRef" :model="goodsForm">
        <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
          <el-select
            placeholder="请选择"
            @change="changeCate(false)"
            v-model="goodsForm.first_cateid"
          >
            <el-option
              v-for="item in store.getters['cate/getCate']"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            />
            <!-- <el-option label="Zone No.2" value="beijing" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
          <el-select placeholder="请选择" v-model="goodsForm.second_cateid">
            <el-option
              v-for="item in cateArr"
              :label="item.catename"
              :value="item.id"
              :key="item.id"
            />
            <!-- <el-option label="Zone No.2" value="beijing" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
          <el-input autocomplete="off" v-model="goodsForm.goodsname" />
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input autocomplete="off" v-model="goodsForm.price" />
        </el-form-item>
        <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
          <el-input autocomplete="off" v-model="goodsForm.market_price" />
        </el-form-item>
        <!-- <el-form-item label="图片" :label-width="formLabelWidth"> -->
        <!--  -->
        <!-- <el-upload action="#" list-type="picture-card" :file-list="fileList" :limit="1">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload> -->

        <!-- <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="预览图片" />
          </el-dialog> -->
        <!--  -->
        <!-- </el-form-item> -->
        <el-form-item label="图片" :label-width="formLabelWidth">
          <!--  -->
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :on-change="onChange"
            :on-remove="onRemove"
            :on-exceed="onExceed"
            :auto-upload="false"
            :file-list="fileList"
            :limit="1"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="预览图片" />
          </el-dialog>
          <!--  -->
        </el-form-item>
        <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
          <el-select
            placeholder="请选择"
            v-model="goodsForm.specsid"
            @change="changeCates(false)"
          >
            <el-option
              v-for="item in store.getters['specs/getSpecs']"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            />
            <!-- <el-option label="Zone No.2" value="beijing" /> -->
          </el-select>
        </el-form-item>
        <!-- multiple	是否多选 -->
        <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
          <el-select multiple placeholder="请选择" v-model="goodsForm.specsattr">
            <el-option v-for="item in specsArr" :key="item" :label="item" :value="item" />
            <!-- <el-option label="Zone No.2" value="beijing" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio-group v-model="goodsForm.isnew">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio-group v-model="goodsForm.ishot">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="goodsForm.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"
              :active-value="1"
              :inactive-value="2"
            />
          </el-tooltip>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(goodsRef)">取消</el-button>
          <el-button type="primary" @click="confirm(goodsRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { goodsadd, goodsinfo, goodsedit } from "../../request/api";
import { ElMessage } from "element-plus";
import { defineProps, defineEmits, ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps, UploadUserFile, UploadFile } from "element-plus";

import { useStore } from "vuex";
let store = useStore();

const formLabelWidth = "140px";
const radio = ref(3);
const value = ref("1");

let props = defineProps({
  isShow: Boolean,
  isAdd: Boolean,
});

// 调用子传父的事件触发
let emit = defineEmits(["cancel"]);
let goodsRef = ref<FormInstance>();
// 封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
  emit("cancel", false);

  goodsForm.value = {
    first_cateid: "", //一级分类编号
    second_cateid: "", //二级分类编号
    goodsname: "", //商品名称
    price: "", //商品价格
    market_price: "", //市场价格
    img: "", //商品图片（文件）
    description: "", //商品描述
    specsid: "", //商品规格编号
    specsattr: "", //商品规格属性
    isnew: 1, //是否新品1是2不是
    ishot: 1, //是否热卖1是2不是
    status: 1, //状态1正常2禁用
  };
  fileList = ref()

  if (!formEl) return;
  // 清除规则验证
  goodsRef.value.resetFields();
};

// 双向绑定的数据
const goodsForm = ref({
  first_cateid: "", //一级分类编号
  second_cateid: "", //二级分类编号
  goodsname: "", //商品名称
  price: "", //商品价格
  market_price: "", //市场价格
  img: "", //商品图片（文件）
  description: "", //商品描述
  specsid: "", //商品规格编号
  specsattr: "", //商品规格属性
  isnew: 1, // 是否新品     1-是 2-否
  ishot: 1, // 是否热卖推荐 1-是 2-否
  status: 1, //状态1正常2禁用
});

// 验证规则
let rules = reactive<FormRules>({
  goodsname: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    {
      min: 2,
      max: 15,
      message: "长度在 2 到 15 个字符",
      trigger: "blur",
    },
  ],
  price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
  market_price: [{ required: true, message: "请输入市场价格", trigger: "blur" }],
  first_cateid: [{ required: true, message: "请选择一级分类", trigger: "change" }],
  second_cateid: [{ required: true, message: "请选择二级分类", trigger: "blur" }],
  specsid: [{ required: true, message: "请选择商品规格", trigger: "change" }],
  specsattr: [{ required: true, message: "请选择规格属性", trigger: "blur" }],
});

// 仓库
let getCate = () => {
  store.dispatch("cate/getCateActions");
};
getCate();
let getSpecs = () => {
  store.dispatch("specs/getSpecsActions");
};
getSpecs();
// console.log(getCate(), "jshdfkjhsadf");

const cateArr = ref([]); // 二级分类
const specsArr = ref([]); // 规格属性的二级分类

// 封装一个一级分类切换事件，用于获取当前选中状态
const changeCate = (n: any) => {
  //思路：知道当前用户选中的id值，拿id去数组中进行查找，找到所在下标，自然获得当前数组下标下的children
  let index = store.getters["cate/getCate"].findIndex(
    (item: any) => item.id == goodsForm.value.first_cateid
  );
  //   console.log(index);
  cateArr.value = store.getters["cate/getCate"][index].children;
  // 点击一级分类清空二级分类
  if (!n) {
    goodsForm.value.second_cateid = "";
  }
};
const changeCates = (e: any) => {
  //拿到当前id去数组中查找当前下标的id 就能获取到当前下标的childrn数据就可以渲染二级分类了
  let index = store.getters["specs/getSpecs"].findIndex(
    (item: any) => item.id === goodsForm.value.specsid
  );
  specsArr.value = store.getters["specs/getSpecs"][index].attrs;
  if (!e) {
    goodsForm.value.specsattr = "";
  }
};

// 数据回显
const lookup = (id: any) => {
  goodsinfo({ id }).then((res: any) => {
    goodsForm.value = res.list;
    goodsForm.value.id = id;
    fileList.value = res.list.img ? [{ url: res.list.img }] : [];
    goodsForm.value.specsattr = goodsForm.value.specsattr.split(",");
    changeCate(true);
    changeCates(true);
  });
};

// 添加和编辑事件
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((val) => {
    if (val) {
      if (props.isAdd) {
        console.log(goodsForm.value);
        // console.log(1);
        // return
        goodsadd(goodsForm.value).then((res) => {
          //   console.log(res,'kdfhkj');
          if (res.code == 200) {
            // console.log(res);
            cancel();
            // 成功 提示
            ElMessage.success(res.msg);
            store.dispatch("goods/getGoodsListActions");
          }
        });
        // return
      } else {
        
      }
    }
  });
};

// 可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性
defineExpose({
  lookup,
});

// 图片上传
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
// 用于清空图片
// const fileList: any = ref([]);
let fileList = ref();

// 上传图片相关的
// 预览
const onPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const onChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  goodsForm.value.img = uploadFile.raw;
};

const onRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  goodsForm.value.img = "";
};

const onExceed: UploadProps["onExceed"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  ElMessage({
    message: "只能上传一张图片",
    type: "error",
  });
};
</script>

<style lang="less" scoped></style>
